package main.java.com.itlin.datastructure.queue;

import java.util.Iterator;

        /**
     * 仅用head，tail判断空满，head,tail需要换算成索引值
     * @param <E>  队列中的元素类型
     */
public class ArrayQueue3<E> implements Queue<E>,Iterable<E>{
    private final E[] array;
    private int  head = 0;
    private int tail = 0;


    @SuppressWarnings("all")
    public ArrayQueue3(int capacity ){
        //1. 抛异常
        if ((capacity & capacity - 1) != 0){
            throw new IllegalArgumentException("capacity 必须是2的幂");
        }
        array =(E[]) new Object[capacity];
    }

    /**
     * head = 0
     * tail =  3 % 3 = 0
     * capacity = 3
     * @return
     */


    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = head;
            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public E next() {
                E value = array[(int)Integer.toUnsignedLong(p) % array.length];
                p++;
                return value;
            }
        };
    }

    @Override
    public boolean offer(E value) {
        if (isFull()){
            return false;
        }

        array[tail & (array.length - 1)] = value;
        tail++;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()){
            return null;
        }
        E value = array[head & (array.length - 1)];
        head++;
        return value;
    }

    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        E value = array[head & (array.length - 1)];
        return value;
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return tail - head == array.length;
    }
}
